// MyIsisClient.cpp: implementation of the CMyIsisClient class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "isismarc.h"
#include "MyIsisClient.h"
#include <afxinet.h>


#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMyIsisClient::CMyIsisClient()
{


}

CMyIsisClient::~CMyIsisClient()
{

}

CString CMyIsisClient::makeConnection(CString operation)
{

	 try
	   {


		  //   1. Instantiate CInternetSession
		  CInternetSession httpSession(_T("Sample Web Service Client"), 
							   1,
							   INTERNET_OPEN_TYPE_PRECONFIG,
							   NULL,
							   NULL,
							   INTERNET_FLAG_DONT_CACHE);
      
		  //   2. Get CHttpConnection (Server URL and Port required)
		  CHttpConnection* pHttpConnection = 
								  httpSession.GetHttpConnection(cip_serveraddress, 
									 INTERNET_FLAG_NO_AUTO_REDIRECT,
									 atoi(cip_serverport), NULL, NULL);


	      CHttpFile* pHttpFile  = 
								  pHttpConnection->OpenRequest
								  ("POST", 
									 "/ismserver/controller.php", 
									 NULL, 1, NULL, NULL, 
									 INTERNET_FLAG_KEEP_CONNECTION |
									 INTERNET_FLAG_EXISTING_CONNECT |
									 INTERNET_FLAG_DONT_CACHE |
									 INTERNET_FLAG_RELOAD);


		  CString sFormData=operation;

		  CString sHeaders="Accept: text/*\r\nUser-Agent: Hack-o-Matic ver 0.01\r\nContent-Type: application/x-www-form-urlencoded\r\n";


		  pHttpFile->SendRequest(
				   sHeaders,
				   (LPVOID)(LPCSTR)sFormData,
				   sFormData.GetLength());

		  //   6. Check the return HTTP Status Code
		  DWORD dwStatucCode = HTTP_STATUS_OK;

		  pHttpFile->QueryInfoStatusCode(dwStatucCode);

		  if(dwStatucCode == HTTP_STATUS_OK)
		  {
			 CString strResponse;
			 TCHAR szBuf[CHUNK_SIZE] = {0};
			 UINT nBytesRead=0;
			 UINT response;

			 //   7. Read the response text
			 do
			 {
				response = pHttpFile->Read((void*) szBuf, CHUNK_SIZE);
				if (response>0)
				{
					nBytesRead+=response;
					CString miresp=szBuf;
					strResponse += miresp.Mid(0,response);
				}
				else
					break;

				//if(nBytesRead < CHUNK_SIZE)
				//   break;
			 }
			 while(true);

			 //if (strResponse.GetLength()>200)
			//	AfxMessageBox(strResponse.Mid(strResponse.GetLength()-200,200));



			if(pHttpFile)
			{
				pHttpFile->Close();
				delete pHttpFile;
				pHttpFile = NULL;
			}

			if(pHttpConnection)
			{
				pHttpConnection->Close();
				delete pHttpConnection;
				pHttpConnection = NULL;
			}

			httpSession.Close();


			return strResponse;
				 	
			 
			 //TODO: Process the response
		  }
		  else
		  {
			 //TODO: Error handling

			if(pHttpFile)
			{
				pHttpFile->Close();
				delete pHttpFile;
				pHttpFile = NULL;
			}

			if(pHttpConnection)
			{
				pHttpConnection->Close();
				delete pHttpConnection;
				pHttpConnection = NULL;
			}


			httpSession.Close();


			return "error";

		  }

		  //   8. Close the stream/connection
		 

	   }
	   catch(CInternetException* exp)
	   {
		  TCHAR lpszErrorMsg[MAX_PATH+2];
		  exp->GetErrorMessage(lpszErrorMsg, MAX_PATH);
		  AfxMessageBox(lpszErrorMsg);
		  return "error";
	   }

}

void CMyIsisClient::returnDatabases(CArray <CString, CString> * respuesta)
{

	if (respuesta->GetSize()>=1)
		respuesta->RemoveAll();


	CString response = this->makeConnection("action=databaselist");

	if (response != "error")
	{
		
			IXMLDOMDocumentPtr pDomDocument;
		

			::CoInitialize(NULL);

			HRESULT hr = pDomDocument.CreateInstance(MSXML::CLSID_DOMDocument);
			if (FAILED(hr))
			{
				 _com_error er(hr);
				 AfxMessageBox(er.ErrorMessage());
				 //EndDialog(1);
			}			
			
	
			_bstr_t bstrString,bstr;
			bstrString = response.AllocSysString();

			pDomDocument->loadXML(bstrString);
			//pDocRoot = pDomDocument->documentElement;


			//if (bstr) SysFreeString(bstr);
			bstr = SysAllocString(L"//database");		


			IXMLDOMNodeListPtr pXMLDomNodeList = NULL;
			pXMLDomNodeList = pDomDocument->selectNodes(bstr);


			

			IXMLDOMNodePtr node;
			
			for (long largo=0;largo<pXMLDomNodeList->Getlength();largo++)
			{
				  
				  node = pXMLDomNodeList->Getitem(largo);				  
				  CString bdd = (LPCTSTR) node->Gettext();
				  
				  respuesta->Add(bdd);

				  //node->Release();

				 // Clean up the string
				  //SysFreeString(value);

				  // Clean up the node and attributes
				
			  
			}


			SysFreeString(bstr);
			SysFreeString(bstrString);

			//pXMLDomNodeList->Release();
			//pDomDocument->Release();

			//delete pXMLDomNodeList;
			//delete pDomDocument;

		


	}


}

long CMyIsisClient::returnNumberOfRecords(CString database)
{

	CString response = this->makeConnection("action=numberofrecords&database="+database);

	if (response != "error")
	{
		
			IXMLDOMDocumentPtr pDomDocument;
		

			::CoInitialize(NULL);

			HRESULT hr = pDomDocument.CreateInstance(MSXML::CLSID_DOMDocument);
			if (FAILED(hr))
			{
				 _com_error er(hr);
				 AfxMessageBox(er.ErrorMessage());
				 //EndDialog(1);
			}			
			
	
			_bstr_t bstrString,bstr;
			bstrString = response.AllocSysString();

			pDomDocument->loadXML(bstrString);
			//pDocRoot = pDomDocument->documentElement;


			//if (bstr) SysFreeString(bstr);
			bstr = SysAllocString(L"//number");		


			IXMLDOMNodeListPtr pXMLDomNodeList = NULL;
			pXMLDomNodeList = pDomDocument->selectNodes(bstr);


			

			IXMLDOMNodePtr node;
			
			node = pXMLDomNodeList->Getitem(0);
			CString number = (LPCTSTR) node->Gettext();
			

			SysFreeString(bstr);
			SysFreeString(bstrString);


			//pXMLDomNodeList->Release();
			//pDomDocument->Release();

			//delete pXMLDomNodeList;
			//delete pDomDocument;

			
			return atol(number);


	}
	else
		return 0;
}


CString CMyIsisClient::returnRecord(CString database, int mfn)
{

	CString mimfn;
	mimfn.Format("%d",mfn);
		
	CString response = this->makeConnection("action=getrecord&database="+database+"&mfn="+mimfn);

	
	if (response != "error")
	{
		
			return response;


	}
	else

		return "";

}
CString CMyIsisClient::returnAllRecords(CString database)
{
    
	
		
	CString response = this->makeConnection("action=getAllRecords&database="+database);

	
//AfxMessageBox(response);
	if (response != "error" && response.GetLength()>40000)
	{
		
			return response;

	}
	else
	{	

		AfxMessageBox("Error de memoria");
		return "";
		
	}
}

long CMyIsisClient::saveRecord(CString database, CString record, CString mfn)
{

	CString response = this->makeConnection("action=saverecord&database="+database+"&mfn="+mfn+"&record="+record);
	//AfxMessageBox(response);

	if (response != "error")
	{
			return -1;
	}
	else

		return 0;

}

//DEL CString CMyIsisClient::returnXMLFDT21(CString database)
//DEL {
//DEL 
//DEL 
//DEL 	CString response = this->makeConnection("action=getfdt21&database="+database);
//DEL 	//AfxMessageBox(record);
//DEL 
//DEL 	return response;
//DEL }

CString CMyIsisClient::createNewRecord(CString database)
{
	CString response = this->makeConnection("action=newrecord&database="+database);

	if (response != "error")
	{
		
			return response;


	}
	else

		return "";
}

